package com.peng.herostory.cmdhanlder;

import com.peng.herostory.model.MoveState;
import com.peng.herostory.model.User;
import com.peng.herostory.model.UserManager;
import com.peng.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WhoElseIsHereCmdHandler implements ICmdHandler<GameMsgProtocol.WhoElseIsHereCmd> {
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.WhoElseIsHereCmd msg) {
        GameMsgProtocol.WhoElseIsHereResult.Builder resultBuilder = GameMsgProtocol.WhoElseIsHereResult.newBuilder();

        for (User user : UserManager.listUser()) {
            if (user == null) {
                return;
            }
            log.info("user:{}", user);
            MoveState moveState = user.getMoveState();
            //当用户载入页面后，前端通过 移动起始时间，计算时间差，得到目前在场英雄所在位置
            GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.Builder moveStateBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.newBuilder()
                    .setFromPosX(moveState.getFromPosX())
                    .setFromPosY(moveState.getFromPosY())
                    .setToPosX(moveState.getToPosX())
                    .setToPosY(moveState.getToPosY())
                    .setStartTime(moveState.getStartTime());
            GameMsgProtocol.WhoElseIsHereResult.UserInfo.Builder userInfoBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo
                    .newBuilder()
                    .setUserId(user.getUserId())
                    .setMoveState(moveStateBuilder)
                    .setHeroAvatar(user.getHeroAvatar());
            resultBuilder.addUserInfo(userInfoBuilder);
        }
        GameMsgProtocol.WhoElseIsHereResult userInfoResult = resultBuilder.build();
        ctx.writeAndFlush(userInfoResult);
    }
}
